package com.demo.controller;

import com.demo.annotation.GlobalInterceptor;
import com.demo.annotation.VerifyParam;
import com.demo.entity.constants.Constants;
import com.demo.entity.dto.CreateImageCode;
import com.demo.entity.dto.SessionWebUserDto;
import com.demo.entity.enums.VerifyRegexEnum;
import com.demo.entity.po.UserInfo;
import com.demo.entity.vo.ResponseVO;
import com.demo.exception.BusinessException;
import com.demo.service.EmailCodeService;
import com.demo.service.UserInfoService;
import com.demo.utils.StringTools;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@RestController("accountController")
public class AccountController extends ABaseController {

    @Resource
    private UserInfoService userInfoService;


    @Resource
    private EmailCodeService emailCodeService;

    /**
     * 获取验证码
     * @param response

     */
   @RequestMapping("/checkCode")
   @GlobalInterceptor(checkLogin =false)
   public void checkCode(HttpServletResponse response,
                         HttpSession session,
                         Integer type) throws IOException {
       CreateImageCode vCode = new CreateImageCode();
       response.setHeader("Pragma", "no-cache");
       response.setHeader("Cache-Control", "no-cache");
       response.setDateHeader("Expires", 0);
       response.setContentType("image/jpeg");
       String code = vCode.getCode();

       if (type == null || type == 0) {// type=0 或者null  表示用户登录
           session.setAttribute(Constants.CHECK_CODE_KEY, code);
       } else { //找回密码 发送邮箱 注册的时候要绑定邮箱
           session.setAttribute(Constants.CHECK_CODE_KEY_EMAIL, code);
       }
       vCode.write(response.getOutputStream());
   }


    /**
     * 发送验证码
     * @param session
     * @param email 邮箱
     * @param checkCode 验证码
     * @param type 0 注册账号是邮箱验证码 1：找回密码验证码
     * @return
     */
   @RequestMapping("/sendEmail")
   @GlobalInterceptor(checkLogin = false,checkParams = true)
   public ResponseVO sendEmail(HttpSession session,
                               @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL, max = 150) String email,
                               @VerifyParam(required = true) String checkCode,
                               @VerifyParam(required = true) Integer type){
       try {
           if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY_EMAIL))) {
               throw new BusinessException("图片验证码不正确");
           }
           emailCodeService.sendEmailCode(email, type);
           return getSuccessResponseVO(null);
       } finally {
           session.removeAttribute(Constants.CHECK_CODE_KEY_EMAIL);
       }
   }


    /**
     * 登录
     * @param session
     * @param account
     * @param password
     * @param checkCode
     * @return
     */
    @RequestMapping("/login")
    @GlobalInterceptor(checkParams = true,checkLogin = false) //是否校验参数
    public ResponseVO login(HttpSession session,
                            @VerifyParam(required = true) String account,
                            @VerifyParam(required = true) String password,
                            @VerifyParam(required = true) String checkCode) {
        try {
            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY))) {
                throw new BusinessException("图片验证码错误");
            }
            SessionWebUserDto sessionWebUserDto = userInfoService.login(account, password);
            session.setAttribute(Constants.SESSION_KEY, sessionWebUserDto);
            return getSuccessResponseVO(sessionWebUserDto);
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }


    /**
     * 注册 账号
     * @param session
     * @param email 邮箱
     * @param account 账户
     * @param password 密码
     * @param checkCode 验证码
     * @param emailCode 邮箱验证码
     * @return
     */
    @RequestMapping("/register")
    @GlobalInterceptor(checkLogin = false, checkParams = true)
    public ResponseVO register(HttpSession session,
                               @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL, max = 150) String email,
                               @VerifyParam(required = true, max = 20) String account,
                               @VerifyParam(required = true, regex = VerifyRegexEnum.PASSWORD, min = 8, max = 18) String password,
                               @VerifyParam(required = true) String checkCode,
                               @VerifyParam(required = true) String emailCode
                               ) {
        try {
            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY))) {
                throw new BusinessException("图片验证码不正确");
            }
            userInfoService.register(email, account, password, emailCode);
            return getSuccessResponseVO(null);
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }


    /**
     * 找回密码
     * @param session
     * @param email
     * @param account
     * @param password
     * @param checkCode
     * @param emailCode
     * @return
     */
    @RequestMapping("/restMyPassword")
    @GlobalInterceptor(checkLogin = false,checkParams = true)
    public ResponseVO restMyPassword(HttpSession session,
                                  @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL, max = 150) String email,
                                  @VerifyParam(required = true, max = 20) String account,
                                  @VerifyParam(required = true, regex = VerifyRegexEnum.PASSWORD, min = 8, max = 18) String password,
                                  @VerifyParam(required = true) String checkCode,
                                  @VerifyParam(required = true) String emailCode){
        try {
            if (!checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY))) {
                throw new BusinessException("图片验证码不正确");
            }
            userInfoService.restMyPassword(email, account, password, emailCode);
            return getSuccessResponseVO(null);
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }

    /**
     * 获取用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/getUserInfo")
    @GlobalInterceptor //是否校验参数
    public ResponseVO getUserInfo(HttpSession session) {
        SessionWebUserDto sessionWebUserDto = getUserInfoFromSession(session);
        UserInfo userInfo = this.userInfoService.getUserInfoByUserId(sessionWebUserDto.getUserId());
        return getSuccessResponseVO(userInfo);
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public ResponseVO logout(HttpSession session) {
        session.invalidate();
        return getSuccessResponseVO(null);
    }

    /**
     * 修改账户密码
     * @param session
     * @param password 密码
     * @return
     */
    @RequestMapping("/updatePassword")
    @GlobalInterceptor(checkParams = true)
    public ResponseVO updatePassword(HttpSession session,
                                     @VerifyParam(required = true ,regex = VerifyRegexEnum.PASSWORD,min = 8,max = 18)String password){
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        UserInfo userInfo = new UserInfo();
        userInfo.setPassword(StringTools.encodeByMD5(password));
        this.userInfoService.updateUserInfoByUserId(userInfo,webUserDto.getUserId());
        return  getSuccessResponseVO(null);
    }

    /**
     * 保存我的信息
     * @param bean
     * @return
     */
    @RequestMapping("/saveMyInfo")
    @GlobalInterceptor
    public ResponseVO saveMyInfo(HttpSession session, UserInfo bean) {
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        bean.setUserId(webUserDto.getUserId());
        this.userInfoService.saveUserInfo(bean);
        return getSuccessResponseVO(null);
    }


    @RequestMapping("/saveImage")
    @GlobalInterceptor
    public ResponseVO saveImage(HttpSession session, String avatar) {
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        UserInfo updateInfo = new UserInfo();
        updateInfo.setAvatar(avatar);
        updateInfo.setUserId(webUserDto.getUserId());
        this.userInfoService.updateUserInfoByUserId(updateInfo,webUserDto.getUserId());
        return getSuccessResponseVO(null);
    }
}
